<template>
  <div>
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      @keyup.enter.native="search()"
    >
      <el-form-item label="活动简介关键字">
        <br />
        <br />
        <el-input
          style="margin-left:-100px;width:200px"
          v-model="formInline.keywords"
          placeholder
        ></el-input>
      </el-form-item>

      <el-form-item label="是否发布">
        <br />
        <br />
        <el-select
          style="margin-left:-70px;width:200px"
          v-model="formInline.status"
        >
          <el-option label="全部" value></el-option>
          <el-option label="已发布" value="2"></el-option>
          <el-option label="未发布" value="1"></el-option>
        </el-select>
      </el-form-item>
      <div style="width:100%;display:flex;justify-content:flex-end;">
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="search()"
            size="mini"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="kong()"
            size="mini"
            icon="el-icon-delete"
            >清空</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="toAdd()"
            icon="el-icon-edit"
            size="mini"
            >创建活动</el-button
          >
        </el-form-item>
      </div>
    </el-form>

    <el-table
      :data="tableData"
      v-loading="loading"
      border
      height="400px"
      style="width: 100%;"
      :header-cell-style="{ background: '#ebecf0', color: '#606266' }"
    >
      <el-table-column
        type="index"
        width="60"
        label="序号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="activityDesc"
        label="活动简介"
        header-align="center"
        width="460"
        fixe
      ></el-table-column>
      <el-table-column
        prop="beginTime"
        label="开始时间"
        header-align="center"
        width="180"
        :formatter="fixData"
      ></el-table-column>
      <el-table-column
        prop="endTime"
        label="截止时间"
        header-align="center"
        width="180"
        :formatter="fixData"
      ></el-table-column>
      <el-table-column label="状态" header-align="center" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.timeStatus == '1'">未开始</span>
          <span v-if="scope.row.timeStatus == '2'">进行中</span>
          <span v-if="scope.row.timeStatus == '3'">已过期</span>
          <!-- <el-tag
                        v-if="scope.row.status != '3' && currentTime < scope.row.beginTime"
                        effect="dark"
                    >未开始</el-tag>
                    <el-tag
                        type="success"
                        v-if="scope.row.status == '2' && scope.row.beginTime < currentTime  && currentTime < scope.row.endTime"
                    >进行中</el-tag>
                    <el-tag type="info" v-if="currentTime > scope.row.endTime">已过期</el-tag>-->
        </template>
      </el-table-column>
      <el-table-column label="方案状态" align="center" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.status == '1'">未发布</span>
          <span v-if="scope.row.status == '2'">已发布</span>
          <span v-if="scope.row.status == '3'">已删除</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createUserName"
        label="创建人"
        align="left"
        width="200"
      ></el-table-column>
      <el-table-column
        label="操作"
        width="380"
        align="center"
        header-align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="updatePlanStatus(scope.row.uuid, '2')"
            v-if="scope.row.status == '1'"
            >发布</el-button
          >
          <el-button
            type="text"
            @click="updatePlanStatus(scope.row.uuid, '1')"
            v-if="scope.row.status == '2'"
            >撤回</el-button
          >
          <el-button
            type="text"
            @click="toEdit(scope.row)"
            v-show="scope.row.status == '1'"
            >编辑</el-button
          >
          <el-button type="text" @click="toEdit2(scope.row)">详情</el-button>
          <el-button type="text" @click="seedetail(scope.row)"
            >参与详情</el-button
          >
          <el-button
            type="text"
            @click="updatePlanStatus(scope.row.uuid, '3')"
            v-if="scope.row.status == '1'"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin-top:5px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 50, 100, 150, 200]"
        :current-page="listQuery.current"
        :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog
      title="参与详情"
      :visible.sync="dialogVisibledetail"
      width="65%"
      custom-class="el-dialog-star"
      top="3vh"
    >
      <el-form
        :inline="true"
        :model="formCoupon"
        class="search-form-inline"
        style="margin-top:-20px;"
      >
        <el-input
          v-model="formCoupon.shopName"
          style="width:200px;"
          placeholder="专卖店名称"
          clearable
        ></el-input>
        <el-input
          v-model="formCoupon.warzoneName"
          style="width:200px;"
          placeholder="大区名称"
          clearable
        ></el-input>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="(listQuery2.current = 1), queryChooseGoodsList()"
          >查询</el-button
        >
        <el-button
          @click="exportToo"
          style="margin-top: 0px;"
          size="mini"
          type="success"
          icon="el-icon-s-data"
          :loading="exportLoading"
          >导出</el-button
        >
      </el-form>
      <el-table
        :data="couponListshop"
        border
        style="font-size: 10px;width:100%;"
        height="300"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="60"
        ></el-table-column>
        <!--<el-table-column prop="couponNo" label="卡券编号" width="200" header-align="center"></el-table-column>-->
        <el-table-column
          prop="authCode"
          label="店铺编码"
          width="120"
          align="left"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="orgName"
          label="专卖店名称"
          width="160"
          align="left"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="warzoneName"
          label="所属大区"
          width="120"
          align="left"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="状态" align="center" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.status == '1'">启用</span>
            <span v-if="scope.row.status == '0'">未启用</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="beginTime"
          label="参与时间"
          align="right"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="endTime"
          label="结束时间"
          align="right"
          width="180"
          :formatter="fixData"
        ></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibledetail = false">取 消</el-button>
        <!-- <el-button type="primary" @click="couponConfirm()">确 定</el-button> -->
      </span>
      <div class="block" style="margin-top:5px;">
        <el-pagination
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          :page-sizes="[10, 20, 30, 50, 100, 150, 200]"
          :current-page="listQuery2.current"
          :page-size="listQuery2.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total2"
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryGoodsActivityList,
  updateGoodsActivityStatus,
  //   updatePlanStatus,
  //   deletePromotion
} from '@/api/memberPrice';
import {
  queryChooseGoodsList,
  saveGoodsActivityWithGoods,
  queryGoodsStoreList,
} from '@/api/memberPriceEdit';
import XLSX from 'xlsx';
export default {
  data() {
    return {
      logininfo: {},
      orgList: [],
      orgSeq: '',
      loading: true,
      exportLoading: false,
      couponListshop: [],
      tableDataExcel: [],
      listQuery2: {
        current: 1,
        size: 100,
      },
      dialogVisibledetail: false,
      uuid: '',
      formCoupon: {
        shopName: '',
        warzoneName: '',
      },
      formInline: {
        keywords: '',
        promotionType: '',
        status: '',
      },
      total: 0,
      total2: 0,
      userId: '',
      listQuery: {
        current: 1,
        size: 100,
      },
      tableData: [],
      currentTime: '',
    };
  },
  mounted() {
    this.promotionList();
  },
  methods: {
    kong() {
      this.formInline.keywords = '';
      this.formInline.status = '';
    },
    seedetail(v) {
      this.dialogVisibledetail = true;
      this.formCoupon = this.$options.data().formCoupon;
      this.uuid = v.uuid;
      let data = {
        size: this.listQuery2.size,
        current: this.listQuery2.current,
        condition: {
          uuid: v.uuid,
          shopName: this.formCoupon.shopName,
          warzoneName: this.formCoupon.warzoneName,
        },
        ascs: [],
        descs: [],
      };
      queryGoodsStoreList(data).then((res) => {
        this.couponListshop = res.records;
        this.total2 = res.total;
      });
    },
    exportToo() {
      this.exportLoading = true;
      this.getDataListExcel();
    },
    getDataListExcel() {
      let data = {
        size: this.total2,
        current: 1,
        condition: {
          uuid: this.uuid,
          shopName: this.formCoupon.shopName,
          warzoneName: this.formCoupon.warzoneName,
        },
        ascs: [],
        descs: [],
      };
      queryGoodsStoreList(data).then((res) => {
        if (res.code == 1) {
          this.tableDataExcel = res.records;
          if (this.tableDataExcel.length > 0) {
            this.exportExcel();
          } else {
            this.$message.error('数据为空无法导出!');
          }
        }
        setTimeout(() => {
          this.exportLoading = false;
        }, 3000);
      });
    },
    //全数据页面导出
    exportExcel() {
      this.exportLoading = true;
      //要导出去的标题
      var that = this;
      var arry = [
        ['店铺编码', '专卖店名称', '所属大区', '状态', '参与时间', '结束时间'],
      ];
      that.tableDataExcel
        .map((a, i) => {
          var _arry = [];
          _arry.push(a.authCode);
          _arry.push(a.orgName);
          _arry.push(a.warzoneName);
          _arry.push(a.status == 1 ? '启用' : '未启用');
          _arry.push(a.beginTime == null ? '' : a.beginTime.toString());
          _arry.push(
            a.endTime == null ? '' : a.endTime.toString().substr(0, 10)
          );
          return _arry;
        })
        .forEach((a) => {
          arry.push(a);
        });
      var sheet = XLSX.utils.aoa_to_sheet(arry);
      sheet['!cols'] = [
        {
          wpx: 160, //A
        },
        {
          wpx: 180, //B
        },
        {
          wpx: 180, //C
        },
        {
          wpx: 180, //D
        },
        {
          wpx: 180, //E
        },
        {
          wpx: 180, //E
        },
      ]; //单元格列宽
      this.exportLoading = false;
      this.openDownloadDialog(
        this.sheet2blob(sheet),
        new Date().toLocaleDateString() + '店铺参与详情记录表.xlsx'
      );
    },
    //转下载文件
    sheet2blob(sheet, sheetName) {
      sheetName = sheetName || 'sheet1';
      var workbook = {
        SheetNames: [sheetName],
        Sheets: {},
      };
      workbook.Sheets[sheetName] = sheet;
      // 生成excel的配置项
      var wopts = {
        bookType: 'xlsx', // 要生成的文件类型
        bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        type: 'binary',
      };
      var wbout = XLSX.write(workbook, wopts);
      var blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
      // 字符串转ArrayBuffer
      function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }
      return blob;
    },
    //下载文件触发弹窗
    openDownloadDialog(url, saveName) {
      if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
      }
      var aLink = document.createElement('a');
      aLink.href = url;
      aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
      var event;
      if (window.MouseEvent) {
        event = new MouseEvent('click');
      } else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent(
          'click',
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        );
      }
      aLink.dispatchEvent(event);
    },
    queryChooseGoodsList() {
      let data = {
        size: this.listQuery2.size,
        current: this.listQuery2.current,
        condition: {
          uuid: this.uuid,
          shopName: this.formCoupon.shopName,
          warzoneName: this.formCoupon.warzoneName,
        },
        ascs: [],
        descs: [],
      };
      queryGoodsStoreList(data).then((res) => {
        this.couponListshop = res.records;
        this.total2 = res.total;
      });
    },
    fixData(row, column, cellValue, index) {
      if (cellValue == null || cellValue == '') return '';
      return cellValue.substring(0, 10);
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.promotionList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.promotionList();
    },
    handleSizeChange2(val) {
      this.listQuery2.size = val;
      this.queryChooseGoodsList();
    },
    handleCurrentChange2(val) {
      this.listQuery2.current = val;
      this.queryChooseGoodsList();
    },
    indexMethod(index) {
      let curpage = this.listQuery.current; //单前页码，具体看组件取值
      let limitpage = this.listQuery.size; //每页条数，具体是组件取值
      return index + 1 + (curpage - 1) * limitpage;
    },
    search() {
      this.listQuery.current = 1;
      this.promotionList();
    },
    promotionList() {
      let data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          //   orgSeq: this.orgSeq,
          keywords: this.formInline.keywords,
          promotionType: this.formInline.promotionType,
          status: this.formInline.status,
        },
        ascs: [],
        descs: [],
      };
      queryGoodsActivityList(data).then((res) => {
        this.loading = false;
        console.log(res.records);
        this.tableData = res.records;
        this.total = res.total;
        this.currentTime = this.format(new Date(), 'yyyy-MM-dd HH:mm:ss');
      });
    },
    format(date, fmt) {
      let o = {
        'M+': date.getMonth() + 1, //月份
        'd+': date.getDate(), //日
        'H+': date.getHours(), //小时
        'm+': date.getMinutes(), //分
        's+': date.getSeconds(), //秒
        'q+': Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds(), //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        );
      for (let k in o)
        if (new RegExp('(' + k + ')').test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ('00' + o[k]).substr(('' + o[k]).length)
          );
      return fmt;
    },
    toAdd() {
      this.$router.push({
        name: 'memberPriceEdit',
        params: {},
      });
    },
    toEdit(item) {
      this.$router.push({
        name: 'memberPriceEdit',
        params: {
          edit: item,
          falg: false,
          updateFlag: true,
        },
      });
    },
    toEdit2(item) {
      this.$router.push({
        name: 'memberPriceEdit',
        params: {
          edit: item,
          falg: true,
        },
      });
    },
    updatePlanStatus(planId, status) {
      var msg = '';
      if (status == '2') {
        msg = '发布';
      } else if (status == '1') {
        msg = '撤回';
      } else if (status == '3') {
        msg = '删除';
      }
      this.$confirm('确定' + msg + '当前方案吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let data = {
            uuid: planId,
            status: status,
          };
          updateGoodsActivityStatus(data).then((res) => {
            if (res.code == '1') {
              this.$message({
                showClose: true,
                message: msg + '成功',
                type: 'success',
              });
              this.promotionList();
            } else {
              this.$message.error(msg + '失败');
            }
            this.loading = false;
          });
        })
        .catch(() => {});
    },
  },
  beforeRouteLeave(to, from, next) {
    // 设置下一个路由的 meta
    to.meta.keepAlive = false; // C 跳转到 A 时让 A 不缓存，即刷新
    next();
  },
};
</script>
<style lang="less" scoped>
.toptitle {
  border: 1px solid #e0e0e0;
  border-bottom: 2px solid #188097;
  background: #f5f5f5;
  line-height: 35px;
  margin-bottom: 10px;
  padding: 0 10px;
  font-size: 14px;
  font-weight: bold;
}
.el-input--small .el-input__inner {
  height: 32px;
  line-height: 32px;
}
.demo-form-inline {
  //   border: 1px solid #ebeef5;
  padding: 20px 10px 0px 30px;
}
.el-dialog-star {
  min-width: 800px;
}
.el-dialog-star .el-dialog__header {
  background: #f5f7fa;
  padding: 15px 20px;
}
.el-dialog-star .el-dialog__body {
  padding: 10px 20px 20px;
}
</style>
